package servlet.sys;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jdbc.DBUtils;
import servlet.UtfUtil;

@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Connection connection = DBUtils.getConn();

		try {
			String username = request.getParameter("username");
			username = new String(username.getBytes("iso-8859-1"), "utf-8");
			// username = UtfUtil.Utf(username);
			String password = request.getParameter("password");
			password = new String(password.getBytes(), "utf-8");

			String loginkeeping = request.getParameter("loginkeeping");

			String sql = "select *  from `user`  WHERE name=? AND  pasword=?";
			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, password);
			ResultSet rs = ps.executeQuery();

			int id = 0;
			while (rs.next()) {
				id = rs.getInt("id");
			}
			int judge = 0;
			if (id > 0) {
				judge = 1;
				HttpSession httpSession = request.getSession();
				httpSession.setAttribute("judge", "ok");
				httpSession.setMaxInactiveInterval(10 * 60);
				response.sendRedirect("NewsListServlet");
				if (loginkeeping != null) {
					Cookie name = new Cookie("username", username);
					Cookie pass = new Cookie("pasword", password);
					name.setMaxAge(30 * 60);
					pass.setMaxAge(30 * 60);
					response.addCookie(name);
					response.addCookie(pass);
				}
			} else {
				HttpSession httpSession = request.getSession();
				httpSession.setAttribute("judge", null);
				response.sendRedirect("index.jsp");

			}
			/*
			 * response.setContentType("application/json"); JSONObject
			 * jsonObject = new JSONObject(); jsonObject.put("judge", judge);
			 * PrintWriter out = response.getWriter();
			 * out.write(jsonObject.toJSONString());
			 */
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
